<?php

namespace App\Http\Middleware;

use Closure;
use App\Repositories\PermissionRepository;
use Illuminate\Support\Facades\Redis;

class CheckPermissions
{
    protected $repository;

//    public function __construct(PermissionRepository $permissionRepository)
//    {
//        $this->repository = $permissionRepository;
//    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $user = Auth()->guard('admin')->user();

        if(Redis::get($user->id) !=session()->getId()){

                abort(403, '当前账户已在其他地方登录');

        }


        if (!$user->is_super) {
            $path = $request->path();
            $that = $this->repository->hasMany($user->id)->filter(function($route) use ($path) {
                return false !== strpos($path, $route);
            });
            if ($that->isEmpty()) {
                $msg = '权限不足，请联系管理员';
                if (!$request->wantsJson()) {
                    abort(403, $msg);
                }
                return response()->json(['code' => 1001, 'msg' => $msg]);
            }
        }
        return $next($request);
    }
}
